package org.hackystat.devcathlon.ui.page.commons.panels.event;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior;
import org.apache.wicket.ajax.markup.html.navigation.paging.AjaxPagingNavigator;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.markup.repeater.data.ListDataProvider;
import org.apache.wicket.util.time.Duration;
import org.hackystat.devcathlon.engine.event.EventScore;
import org.hackystat.devcathlon.engine.match.Match;

/**
 * Events panel.
 * 
 * @author Anthony Du
 */
public class EventsPanel extends Panel {

  /** Support serialization. */
  private static final long serialVersionUID = 1L;

  /**
   * Set up the listing of the Events.
   * 
   * @param id The Wicket id from the html file.
   * @param match The match
   */
  public EventsPanel(String id, Match match) {
    super(id);
    String noEvents = "";
    List<EventScore> scoresList = new ArrayList<EventScore>();
    if (match.getEventScores().isEmpty()) {
      noEvents = "";
    }
    // Event scores.
    for (EventScore s : match.getEventScores()) {
      scoresList.add(s);
    }
    // Match events.
    DataView scoreView = new DataView("matchEvents", new ListDataProvider(scoresList)) {
      /** Support serialization. */
      private static final long serialVersionUID = 1L;

      @Override
      protected void populateItem(Item item) {
        EventScore scoreItem = (EventScore) item.getModelObject();
        try {
          item.add(new Label("eventDate",  scoreItem.getTimestamp().toString()));
        }
        catch (Exception e) {
          e.printStackTrace();
        }
        item.add(new Label("eventTeam", scoreItem.getTeam().getName()));
        item.add(new Label("teamPoints", String.valueOf(scoreItem.getBaseScore())));
        item.add(new Label("eventDesc", scoreItem.getExplanation()));
      }

    };
    scoreView.setItemsPerPage(3);
    // Create mark-up container for AJAX refresh.
    final WebMarkupContainer eventsContainer = new WebMarkupContainer("eventsContainer");
    eventsContainer.setOutputMarkupId(true);
    eventsContainer.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(5)));
    eventsContainer.add(scoreView);
    eventsContainer.add(new Label("noEvents", noEvents));

    AjaxPagingNavigator pager = new AjaxPagingNavigator("navigator", scoreView) {
      /** Support Serialization. */
      private static final long serialVersionUID = 1L;

      protected void onAjaxEvent(AjaxRequestTarget target) {
        target.addComponent(eventsContainer);
      }
    };
    eventsContainer.add(pager);
    add(eventsContainer);
  }
}
